#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:student_dao.py
# author:张世航
# datetime:2024/12/20 23:50
# software: PyCharm
"""
this is function  description 
"""


# dao/student_dao.py
import pymysql
from config.config import DATABASE_CONFIG
from models.student import Student

def connect_db():
    """连接数据库"""
    try:
        connection = pymysql.connect(**DATABASE_CONFIG)
        return connection
    except pymysql.MySQLError as e:
        print(f"Error connecting to database: {e}")
        return None

def add_student(student):
    """添加学生信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "INSERT INTO student (Sno, Sname, Ssex, Sage, Dno, Sclass, address) VALUES (%s, %s, %s, %s, %s, %s, %s)"
                cursor.execute(sql, (student.Sno, student.Sname, student.Ssex, student.Sage, student.Dno, student.Sclass, student.address))
                connection.commit()
                print("Student added successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error adding student: {e}")
        finally:
            connection.close()

def delete_student(Sno):
    """根据学生学号删除信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "DELETE FROM student WHERE Sno = %s"
                cursor.execute(sql, (Sno,))
                connection.commit()
                print("Student deleted successfully.")
        except pymysql.MySQLError as e:
            connection.rollback()
            print(f"Error deleting student: {e}")
        finally:
            connection.close()

def query_student_by_name(name):
    """根据姓名查询信息"""
    connection = connect_db()
    if connection:
        try:
            with connection.cursor() as cursor:
                sql = "SELECT * FROM student WHERE Sname = %s"
                cursor.execute(sql, (name,))
                results = cursor.fetchall()
                for row in results:
                    print(row)
        except pymysql.MySQLError as e:
            print(f"Error querying student: {e}")
        finally:
            connection.close()